package com.fc.push.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fc.persistence.exception.IDBException;

public class SharedMqttClientPoolFacade {
	
	private static Logger logger = LoggerFactory.getLogger(SharedMqttClientPoolFacade.class);
	
	private static SharedMqttClientPoolImpl poolImpl = null;
	
	private static Object syncObj = new Object();
	
	private static final String DEFAULT_CLIENT_ID = "default_client";
	
	private SharedMqttClientPoolFacade(){}
	
	public static void initPoolImpl(){
		if(poolImpl == null){
			poolImpl = new SharedMqttClientPoolImpl(getServerURI(MqttConfig.getHost(), MqttConfig.getPort()));
		}
	}
	
	/**
	 * 获取redis链接
	 * 
	 * @return
	 */
	private static MqttClient getMqttClientProxy() {
		synchronized (syncObj) {
			if (poolImpl != null) {
				return poolImpl.getResource();
			} else {
				poolImpl = new SharedMqttClientPoolImpl(getServerURI(MqttConfig.getHost(), MqttConfig.getPort()));
				return poolImpl.getResource();
			}
		}
	}
	
	public static MqttClient getMqttClient() {
		MqttClient client = null;
		try {
			client = getMqttClientProxy();
			logger.info("idle:" + poolImpl.getPoolIdles() + " active:" + poolImpl.getPoolActives() + " waiters"
					+ poolImpl.getPoolWaiters());
		} catch (Exception e) {
			throw new IDBException(e.getMessage(), e);
		}
		if (client == null) {
			client = createMqttClient();
		}
		return client;
	}
	
	public static void returnResource(MqttClient client){
		poolImpl.returnResource(client);
	}
	
	public static void closeMqttClientPool(){
		poolImpl.closePool();
	}
	
	protected static MqttClient createMqttClient(){
		MqttConnectOptions options = new MqttConnectOptions();
		options.setCleanSession(MqttConfig.isCleanSession());
		options.setConnectionTimeout(MqttConfig.getConnectTimeOut());
		options.setKeepAliveInterval(MqttConfig.getKeepAliveInterval());
		if(MqttConfig.getUsername() != null && !MqttConfig.getUsername().isEmpty()){
			options.setUserName(MqttConfig.getUsername());
			options.setPassword(MqttConfig.getPassword().toCharArray());
		}
		MqttClient client = null;
		try {
			client = new MqttClient(getServerURI(MqttConfig.getHost(), MqttConfig.getPort()), DEFAULT_CLIENT_ID, new MemoryPersistence());
			client.connect(options);
		} catch (MqttException e) {
			logger.error(e.getMessage());
		}
		return client;
	}
	
	protected static String getServerURI(String ip,int port){
		return "tcp://" + ip + ":" + port;
	}
}
